<template>
  <div>
    <Page auto-content-height>
      <FosoCard :showheader="false" class="!px-0 !pt-0">
        <FosoForm
          ref="formRef"
          :form-columns="formColumns"
          :form-columns-num="8"
          :form-data="formData"
          :form-expand="true"
          label-position="right"
          label-width="auto"
          @search-handle="searchHandle"
        />
      </FosoCard>
      <!-- 表格 -->
      <FosoTable
        ref="positionTable"
        :columns="columns"
        :request-api="getpositionListData"
        :toolbarbutton-name="$t('sys.position.addPosition')"
        @add="addPosition()"
        @delete="DeleteHandle($event)"
        @edit="EditHandle($event)"
      />
    </Page>
    <!-- 弹窗框 -->
    <Drawer class="w-[40%]" @refresh="reloadTable" />
  </div>
</template>

<script setup lang="tsx">
import type { positionQueryType, PositionTypeItem } from './type';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { ElSwitch } from 'element-plus';

import {
  deletePosition,
  getPositionList,
  updatePosition,
} from '#/api/sys/position';

import { formColumns } from './columns';
import ExtraDrawer from './components/drawer.vue';

const positionTableRef = useTemplateRef('positionTable');
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});
// 表单实例
const formRef = ref();
// 表单数据
const formData = ref<positionQueryType>({});
// 表格获取数据
const getpositionListData = async (params: any) => {
  const { page = 1, pageSize = 5 } = params;
  const res: any = await getPositionList({
    page,
    pageSize,
    ...formData.value,
  });
  return {
    total: res.total,
    items: res.data,
  };
};

// 表格配置项
const columns = [
  {
    type: 'checkbox',
    width: 50,
  },
  {
    title: $t('sys.position.name'),
    field: 'name',
  },
  {
    title: $t('sys.position.code'),
    field: 'code',
  },
  {
    title: $t('sys.role.remark'),
    field: 'remark',
  },
  {
    title: $t('sys.department.sort'),
    field: 'sort',
  },
  // 状态
  {
    title: $t('sys.department.status'),
    field: 'status',
    slots: {
      default: ({ row }: any) => {
        return (
          <ElSwitch
            active-text={$t('sys.menu.on')}
            inactive-text={$t('sys.menu.off')}
            inline-prompt
            modelValue={Boolean(row.status)}
            onUpdate:modelValue={() => changeStatus(row)}
          />
        );
      },
    },
  },
  // 创建时间
  {
    title: $t('sys.menu.createTime'),
    field: 'createTime',
    width: 180,
    formatter: ['formatDate', 'yyyy-MM-dd'],
  },
  {
    title: $t('sys.menu.operation'),
    width: 200,
    slots: { default: 'action' },
  },
];

/**
 * @author Buke
 * @description 新增职位
 * @returns {void}
 */
const addPosition = (): void => {
  drawerApi.setState({ title: $t('sys.position.addPosition') });
  drawerApi.setData({ type: 'addData' });
  drawerApi.open();
};

/**
 * @author Buke
 * @description 编辑职位
 * @param {PositionInfo} row - 要编辑的行数据对象，包含职位相关信息。
 * @returns {void}
 */
const EditHandle = (row: PositionTypeItem): void => {
  drawerApi.setState({ title: $t('sys.position.editPosition') });
  drawerApi.setData({ type: 'editData', id: row.id });
  drawerApi.open();
};

/**
 * @author Buke
 * @description 搜索职位
 * @returns {void}
 * @todo 职位查询问题
 */
const searchHandle = (): void => {
  positionTableRef.value?.gridApi.query();
};

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  positionTableRef.value?.gridApi.query();
  drawerApi.close();
};

/**
 * @author Buke
 * @description 切换状态
 * @param {PositionInfo} row - 要切换状态的行数据。
 * @returns {void}
 */
async function changeStatus(row: PositionTypeItem): Promise<void> {
  await updatePosition({
    id: row.id,
    status: Number(!row.status),
  });
  row.status = row.status ? 0 : 1; // 切换状态，确保为 number 类型
  ElMessage.success($t('common.operateSuccess'));
}

/**
 * @author Buke
 * @description 删除职位
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: PositionTypeItem): Promise<void> {
  await deletePosition(row.id as number);
  ElMessage.success($t('common.deleteSuccess'));
  positionTableRef.value?.gridApi.query();
}
</script>
